package com.cloud.demo2020.controller;

import com.cloud.demo2020.common.ResultBean;
import com.cloud.demo2020.entity.AuthCode;
import com.cloud.demo2020.mapper.AuthCodeMapper;
import com.cloud.demo2020.service.MailService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@RestController
public class CodeController {

    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Autowired
    private MailService mailService;

    @RequestMapping("/code/create/{email}")
    public ResultBean create(@PathVariable("email") String email) {
        AuthCode item = new AuthCode();
        item.setEmail(email);
        item.setCode(RandomStringUtils.randomNumeric(6));
        item.setCreatetime(new Date());
        LocalDateTime expire = LocalDateTime.now().plusMinutes(10);
        item.setExpiretime(expire);
        this.authCodeMapper.insert(item);
        //String url = "http://email-service/email/" + email + "/" + item.getCode();
        ResultBean r = this.mailService.send(email, item.getCode());

        return new ResultBean(r.getData());
    }

    @RequestMapping("/code/valid/{email}/{code}")
    public ResultBean valid(@PathVariable("email") String email,
            @PathVariable("code") String code) {
        AuthCode item = new AuthCode();
        item.setEmail(email);
        item.setCode(code);
        Date expire = this.authCodeMapper.selectMaxExpire(item);
        if (expire == null) {
            return new ResultBean(1);
        }
        Date now = new Date();
        return new ResultBean(now.before(expire) ? 0 : 2);
    }
}
